package com.bdqn.Di2Zhan;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 第二章实战2
 */
public class phoneAdd {
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();

            Document doc = builder.parse("src/main/java/com/bdqn/Di2Zhan/entity/phone.xml");

            Element element = doc.createElement("Brand");
            element.setAttribute("name" , "三星");

            Element typeElement = doc.createElement("Type");
            typeElement.setAttribute("name" , "NoteX");

            element.appendChild(typeElement);
            Element phoneElement = (Element) doc.getElementsByTagName("PhoneInfo").item(0);
            phoneElement.appendChild(element);

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            DOMSource domSource = new DOMSource(doc);

            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");

            StreamResult result = new StreamResult(new FileOutputStream("src/main/java/com/bdqn/Di2Zhan/entity/phone.xml"));

            transformer.transform(domSource,result);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }
}
